package net.zoneland.geological.station.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import net.zoneland.geological.project.service.Tbl_zhtServiceI;
import net.zoneland.geological.station.entity.Tbl_station_image;
import net.zoneland.geological.station.entity.Tbl_station_info;
import net.zoneland.geological.station.service.Tbl_station_imageServiceI;
import net.zoneland.geological.station.service.Tbl_station_infoServiceI;
import net.zoneland.geological.station.service.Tbl_station_warn_configServiceI;
import net.zoneland.geological.usermanage.entity.Tbl_user;
import net.zoneland.geological.usermanage.service.Tbl_user_datapermissionServiceI;
import net.zoneland.greenleaf.common.pagination.Pagination;
import net.zoneland.greenleaf.system.controller.BaseController;

/**
 * 设备信息操作控制层(Controller|Action)

 * 表   名：TBL_STATION_INFOCONTROLLER<br/>
 * 注   释：设备信息<br/>
 * 作   者：李义<br/>
 * 日   期：2017-06-03 07:17:46
**/
@Controller
@RequestMapping("tbl_station_info")
public class Tbl_station_infoController extends BaseController { 

	/**
	 * 如果需要系统对此Controller的访问进行监控，记录服务访问的时间，耗时，那么请将monitor属性设置为“true”
	 */

	public boolean monitor = false; 

	private static Logger logger = Logger.getLogger(Tbl_station_infoController.class);

	//获取类的名称
	@SuppressWarnings("unused")
	private String clazzName = new Object() {
		public String getClassName() {
			String clazzName = this.getClass().getName();
			return clazzName.substring(0, clazzName.lastIndexOf('$'));
		}
	}.getClassName();

	/**
	 * tbl_station_infoService
	 * @param tbl_station_infoService
	**/
	@Autowired
	private Tbl_station_infoServiceI tbl_station_infoService;

	@Autowired
	private Tbl_zhtServiceI tbl_zhtServiceI;
	
	@Autowired
	private Tbl_station_warn_configServiceI tbl_station_warn_configServiceI;
	
	@Autowired
	private Tbl_station_imageServiceI tbl_station_imageServiceI;
	
	@Autowired
	private Tbl_user_datapermissionServiceI tbl_user_datapermissionService;
	
	/**
	 * 根据ID获取信息数据
	 * @param id
	 * @return
	**/
	@RequestMapping( method = RequestMethod.GET, value = "/{id}", produces = "text/html;charset=UTF-8" )
	@ResponseBody
	public Object get( @PathVariable("id") String id ){
		Map<String, Object> map = new HashMap<String, Object>();
		Tbl_station_info entity = null;
		Boolean check = true;

		map.put("id", id);
		if( id == null || "(0)".equals( id ) || id.isEmpty() ){
			check = false;
			map.put("result", "error");
			map.put("message", "系统获取到的ID不正常，ID:" + id );
		}
		if( check ){
			try {
				entity = tbl_station_infoService.get( map );
			} catch (Exception e) {
				check = false;
				map.put("result", "error");
				map.put("message", "系统根据ID获取对象失败!");
				logger.error("系统根据ID获取对象发生异常。ID:" + id, e);
			}
		}
		if( check ){
			if( entity != null ){
				map.put( "result", "success");
				map.put( "data", entity );
			}else{
				map.put( "result", "error");
				map.put( "message", "数据不存在！ID:" + id );
			}
		}
		return map;
	}
	
	/**
	 * 根据ID获取信息数据
	 * @param id
	 * @return
	**/
	@RequestMapping( method = RequestMethod.GET, value = "/station/{id}", produces = "text/html;charset=UTF-8" )
	@ResponseBody
	public Object getByStationId( @PathVariable("id") String id ){
		Map<String, Object> map = new HashMap<String, Object>();
		Tbl_station_info entity = null;
		Boolean check = true;

		map.put("station_id", id);
		if( id == null || "(0)".equals( id ) || id.isEmpty() ){
			check = false;
			map.put("result", "error");
			map.put("message", "系统获取到的station_id不正常，station_id:" + id );
		}
		if( check ){
			try {
				entity = tbl_station_infoService.get(map);
			} catch (Exception e) {
				check = false;
				map.put("result", "error");
				map.put("message", "系统根据station_id获取对象失败!");
				logger.error("系统根据station_id获取对象发生异常。station_id:" + id, e);
			}
		}
		if( check ){
			if( entity != null ){
				map.put( "result", "success");
				map.put( "data", entity );
			}else{
				map.put( "result", "error");
				map.put( "message", "数据不存在！station_id:" + id );
			}
		}
		return map;
	}

	/**
	 * 获取设备信息列表
	 * 返回JSON格式数据，如果不需要分页，您可以考虑将pagesize设置为足够大的数字，系统默认为20
	 * @param Map<String, Object> paramMap
	**/
	@RequestMapping( method = RequestMethod.POST, value = "/list" )
	@ResponseBody
	public Object list( @RequestBody Map<String, Object> paramMap ) {
		String page = "1";
		Integer pagesize = 20, totalRecord=0;
		List<Tbl_station_info> list  = null;
		Map<String, Object> map =new HashMap<String,Object>();
		Map<String, Object> query_map =new HashMap<String,Object>();
		Pagination<?> pagination = null;
		Boolean check = true;
		List<String> ids = null;
		
		List<String> visibleStationIds  = null;
		Tbl_user tbl_user = null;
		
		if( paramMap == null ){
			check = false;
			map.put( "result", "error");
			map.put( "message", "参数列表为空，无法进行数据查询!");
		}
		
		if( check ){	
			if( this.getSession().getAttribute( "login_user" ) != null ) {
				tbl_user = (Tbl_user)this.getSession().getAttribute( "login_user" );
			}else {
				check = false;
				map.put( "result", "error" );
				map.put( "login", false );
				map.put( "message", "用户未登录!" );
			}
		}
		
		if( check ){	
			//先查询用户可以访问到的所有设备ID列表
			try {
				visibleStationIds = tbl_user_datapermissionService.getStationIdsWithPermission( tbl_user.getLogin_name() );
				if( visibleStationIds != null && !visibleStationIds.isEmpty() ) {
					paramMap.put( "station_ids", visibleStationIds );
				}else {
					paramMap.put( "station_ids", new String[] {"无"} );
				}
			} catch (Exception e ) {
				check = false;
				map.put( "result", "error" );
				map.put( "message", "系统根据根据用户信息获取数据权限时发生异常!" );
				logger.error( e );
			}
		}
		
		if( check ){
			if( paramMap.get( "tree_level" ) != null ){
				if( "0".equals( paramMap.get( "tree_level" ).toString() )){
					//城市（深圳 - 440300）
				} else if( "1".equals( paramMap.get( "tree_level" ).toString() )){
					//项目ID， 先从zht表里查询出所有的灾害体ID列表
					query_map.put( "project_id", paramMap.get( "tree_id" ).toString() );
					ids = tbl_zhtServiceI.getIds( query_map );
					if( ids != null && !ids.isEmpty() ){
						paramMap.put( "zht_ids", ids);
					}else {
						paramMap.put( "zht_ids", new String[] {"无"});
					}
				} else if( "2".equals( paramMap.get( "tree_level" ).toString() )){
					//灾害点ID
					paramMap.put( "zht_id", paramMap.get( "tree_id" ).toString());
				}
			}			
		}
		if( check ){
			if( paramMap.get( "page" )!=null){
				page = paramMap.get( "page" ).toString();
			}
			if( paramMap.get( "pagesize") != null){
				try{
					pagesize = Integer.parseInt(paramMap.get( "pagesize" ).toString());
				}catch( Exception e ){
					pagesize = 20;
				}
			}
		}
		if( check ){
			try{
				totalRecord = tbl_station_infoService.getListCount( paramMap );
			}catch( Exception e ){
				check = false;
				map.put( "result", "error");
				map.put( "message", "系统根据条件查询信息数据条目总数时发生异常!");
				logger.error( e );
			}
		}
		if( check ){
			try{
				pagination = Pagination.newPagination( pagesize, page, totalRecord );
				paramMap.put( "startRow", pagination.getStartRow() );
				paramMap.put( "pageSize", pagesize );
				/**
			 	* 如果需要按某列进行排序，可以再多给两个参数：orderColName, orderType
			 	* paramMap.put( "orderColName", "ID");
			 	* paramMap.put( "orderType", "DESC");
			 	**/
			}catch( Exception e ){
				check = false;
				map.put( "result", "error" );
				map.put( "message", "系统根据条件进行分页信息计算时发生异常！" );
				logger.error( e );
			}
		}
		if( check ){	
			if( totalRecord>0 ){
				try{
					list = tbl_station_infoService.getList( paramMap );
				}catch( Exception e ){
					check = false;
					map.put( "result", "error" );
					map.put( "message", "系统根据条件进行信息列表查询信息数据时发生异常!" );
					logger.error( e );
				}
			}
		}
		if( check ){
			if( list == null ){
				list = new ArrayList<Tbl_station_info>();
			}
		}
		if( check ){
			map.put( "result", "success" );
			map.put( "message", "系统查询信息数据成功!" );
			map.put( "pagination", pagination );
		}
		map.put( "data", list );
		return map;
}

	/**
	 * 增加或编辑一个设备信息信息
	 * 返回JSON格式数据
	 * @param entity
	**/
	@RequestMapping( method = RequestMethod.POST, value = "/save" )
	@ResponseBody
	public Object save( @RequestBody Map<String, Object> paramMap ){
		Map<String, Object> map = new HashMap<String, Object>();
		Tbl_station_info entity = null;
		Boolean check = true;

		if( paramMap == null ){
			check = false;
			map.put( "result", "error");
			map.put( "message", "需要保存的信息数据为空!");
		} else {
			try {
				entity = (Tbl_station_info)mapToObject( paramMap, Tbl_station_info.class );
			} catch (Exception e) {
				check = false;
				map.put( "result", "error");
				map.put( "message", "将数据转换为对象时发生异常!");
				logger.error( "将数据转换为对象时发生异常!", e );
			}
		}
		if( check ){
			map = validate( entity, map );
			if( map.get( "result" ) == null || "error".equalsIgnoreCase( map.get( "result" ).toString() ) ){
				check = false;
			}
		}
		if( check ){
			try{
				entity = tbl_station_infoService.addOrUpdate( entity );
				map.put( "result", "success");
				map.put( "message", "保存设备信息信息数据成功!");
				map.put( "data", entity );
			}catch( Exception e ){
				check = false;
				map.put( "result", "error" );
				map.put( "message", "保存设备信息信息数据失败!" );
				logger.error("保存设备信息信息数据失败!", e);
			}
		}
		if( check ){
			//如果设备添加成功，那么要考虑检查一下该设备的各项预警值是否都存在，如果不存在，则进行新增，如果有多余的，那么就删除
			try{
				tbl_station_warn_configServiceI.checkConfig( entity.getStation_id() );
			}catch( Exception e ){
				map.put( "result", "error" );
				map.put( "message", "保存设备信息信息时检查预警参数配置失败!" );
				logger.error("保存设备信息信息时检查预警参数配置失败!", e);
			}
		}
		return map;
	}

	/**
	 * 对需要进行保存的对象里的信息校验
	 * @param entity
	 * @param map 
	 * @return
	 */
	private Map<String, Object> validate( Tbl_station_info entity, Map<String, Object> map ) {
		//TODO 这里进行所有的数据校验工作
		map.put("result", "success");
		return map;
	}

	/**
	 * 根据ID删除一个设备信息信息
	 * 返回JSON格式数据
	 * @param int id
	**/
	@RequestMapping( method = RequestMethod.DELETE, value = "/{id}" )
	@ResponseBody
	public Object deleteById( @PathVariable( "id" ) String id ){
		Map<String, Object> map = new HashMap<String, Object>();
		Tbl_station_info entity = null;
		Boolean check = true;

		map.put( "id", id );
		if( id == null || id.isEmpty() || "id".equalsIgnoreCase( id )){
			check = false;
			map.put( "result", "error" );
			map.put( "message", "需要删除的信息ID为空!" );
		}
		if( check ){
			try {
				entity = tbl_station_infoService.get( map );
				if( entity == null ){
					check = false;
					map.put( "result", "error" );
					map.put( "message", "需要删除的信息数据不存在失败!ID:" + id );
				}
			} catch (Exception e) {
				check = false;
				map.put( "result", "error" );
				map.put( "message", "根据ID查询需要删除的信息数据失败!ID:" + id );
				logger.error( "根据ID查询需要删除的信息数据失败!ID:" + id, e);
			}
		}
		if( check ){
			try {
				tbl_station_infoService.delete( map );
				map.put( "result", "success" );
				map.put( "message", "成功删除一个信息数据!" );
			} catch (Exception e) {
				check = false;
				map.put( "result", "error");
				map.put( "message", "删除信息数据失败!ID:" + id );
				logger.error( "删除信息数据失败!ID:" + id, e);
			}
		}
		if( check ){
			//如果设备添加成功，那么要考虑检查一下该设备的各项预警值是否都存在，如果不存在，则进行新增，如果有多余的，那么就删除
			try{
				tbl_station_warn_configServiceI.checkConfig( entity.getStation_id() );
			}catch( Exception e ){
				map.put( "result", "error" );
				map.put( "message", "删除设备信息时检查预警参数配置失败!" );
				logger.error("删除设备信息时检查预警参数配置失败!", e);
			}
		}
		return map;
	}
	
	@RequestMapping("/mapStation/{id}")
	public String mapStation(@PathVariable("id") String id, HttpServletRequest request) throws Exception {
		
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("id", id);
		Tbl_station_info station_info = tbl_station_infoService.get(paramMap);
		
		Map<String, Object> paramMap1 = new HashMap<>();
		paramMap1.put("station_id", id);
		paramMap1.put("is_default", 1);
		List<Tbl_station_image> station_imgs = tbl_station_imageServiceI.getList(paramMap1);
		
		request.setAttribute("station", station_info);
		
		if (station_imgs != null && station_imgs.size() > 0) {
			request.setAttribute("stationImgUrl", station_imgs.get(0).getImage_url());
		} else {
			request.setAttribute("stationImgUrl", "a.jpg");
		}
		
		return "pages/geological/map_station_frame";
	}
}
